package uit.edu.vn.Activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;

import uit.edu.vn.Contact.imContact;
import uit.edu.vn.Model.FileObject;
import uit.edu.vn.Model.myFile;
import uit.edu.vn.Utility.AESControl;
import uit.edu.vn.Utility.CheckInternet;
import uit.edu.vn.Utility.Contact;
import uit.edu.vn.Utility.MyActivity;
import uit.edu.vn.Utility.WebService;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ContactRestoreServerActivity extends MyActivity implements OnItemClickListener{
	private ListView listview;
	private Context context;
	private TextView titleHeader;
	private Resources res;
	private ProgressDialog loadingContactDialog;
	private String path = Environment.getExternalStorageDirectory()+"/BackupManager/Contact";
	private ArrayList<myFile> listFiles = new ArrayList<myFile>();
	private int numberOfItemSelected = 0;	
	private AESControl aes;
	private ArrayAdapter<myFile> arrayAdapter;
	ArrayList<FileObject> flist = new ArrayList<FileObject>();
	ArrayAdapter<FileObject> alist;
    private String userid = "";
    private String username = "";
    private String password = "";
    private static final String STRING_NAME_USERSETTING = "USER REFERENCES";
    private SharedPreferences ShareRef = null;
	int type = 1;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
        username = getSetting("username");
        password = getSetting("password");
        userid   = getSetting("userid");
        
        setContentView(R.layout.backup_file);
        //kiem tra neu username va password rong thi ket thuc activity hien tai va goi activity login
      if(username.equals("") && password.equals("")){
          Intent intent = new Intent(ContactRestoreServerActivity.this, LoginActivity.class);
          startActivity(intent);
          this.finish();            	
      }	
      
      System.out.println("ContactRestoreServerActivity");
      System.out.println("username: "+ username);
      System.out.println("password: "+ password);
      System.out.println("MainActivity.address.toString() : " + MainActivity.address.toString());
      
        titleHeader=(TextView)findViewById(R.id.txt_titleFile);
        titleHeader.setText(R.string.title_RestoreHeaderContactServer);
        listview =(ListView)findViewById(R.id.listFileBackup);
        res=getResources();	
        context=getBaseContext();	
        loadingContactDialog= new ProgressDialog(this);
        loadingContactDialog.setMessage("Đang tải dữ liệu từ máy chủ");
        loadingContactDialog.setCancelable(false);
        loadingContactDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        CheckInternet chkI= new CheckInternet(context);
        if(chkI.checkStatus().equals(true))
		{

        	new BackgroundTask().execute();
        	if(listFiles == null){
        		showToast("Không có danh bạ sao lưu");
        	}
        	
		}
        else
        {
        	Log.d("ketnoi", "ko co ket noi internet");
        	showToast("Khong co ket noi internet");
        
        }
	
	        listview.setOnCreateContextMenuListener(this);
	        listview.setOnItemClickListener( this);
	        listview.setOnItemClickListener(new OnItemClickListener() 
	        {
	     	   @Override
	     	   public void onItemClick(AdapterView<?> arg0, View arg1, final int position,
	 			long arg3) {
	     		   
	     		   	try {
	     		   		
								// TODO Auto-generated method stub

								myFile entry = listFiles.get(position);
								File temp = new File(entry.getPath());
								final Dialog dialog=new Dialog(ContactRestoreServerActivity.this);
				 	    		dialog.setContentView(uit.edu.vn.Activity.R.layout.file_dialog_server);
				 	    		dialog.setTitle("Thông tin tập tin ");
				 	    		TextView txt_filename= (TextView)dialog.findViewById(R.id.txt_filenameDialog);
				 	    		TextView txt_filesize= (TextView)dialog.findViewById(R.id.txt_filesizeDialog);
				 	    		TextView txt_fileday=(TextView)dialog.findViewById(R.id.txt_filedayDialog);
				 	    		String day=flist.get(position).dayBackupFile;
				 	    		txt_fileday.setText(day);
				 	    		txt_filename.setText(temp.getName());
				 	    		int size_temp=Integer.parseInt(entry.getSize());
				 	    		System.out.println(size_temp);
			                	if(size_temp<1024)
			                	{
			                		txt_filesize.setText(entry.getSize()+" Byte");   
			                	}
			                	else if(size_temp<1048576)
			                	{
			                		System.out.println(size_temp);
			                		size_temp=size_temp/1024;
			                		System.out.println(size_temp);
			                		txt_filesize.setText(size_temp+" KB"); 
			                	}
			                	else
			                	{
			                		size_temp=size_temp/1048576;
			                		txt_filesize.setText(size_temp+" MB"); 
			                	}
				 	    		//txt_filesize.setText(entry.getSize()+"byte");
				 	    		
				 	    		Button btn_ok = (Button)dialog.findViewById(R.id.btn_okDialog);
				 	    		btn_ok.setOnClickListener(new View.OnClickListener() {
									
									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										dialog.dismiss();
									}
								});
				 	    		dialog.show();
							}
					
	     		   	 catch (Exception e) {
						// TODO: handle exception
						  e.printStackTrace();
					}
	     		   	
			
	     	   }
	        });
			
		}
	
	private class BackgroundTask extends AsyncTask<Void, Void, Void>
	{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			loadingContactDialog.show();
		}
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
			
				flist = WebService.getAllList(Integer.parseInt(userid), type);
				for(int i = 0;i<flist.size(); i++){
					System.out.println("file name is: "+flist.get(i).getFileName());
				}
				convert(flist);//convert tu fileObject sang myFile
			}
				catch (Exception e) {
					// TODO: handle exception
					e.fillInStackTrace();
				}
				
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			loadingContactDialog.dismiss();
			arrayAdapter = new ArrayAdapter<myFile>(context, R.layout.row_file, listFiles) {
	            @Override
	            public View getView(int position, View v, ViewGroup parent) {
	                if (v == null) {
	                    LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	                    v = vi.inflate(R.layout.row_file, null);
	                }
	                myFile ffile = listFiles.get(position);                
	                if(ffile!=null){
	                    TextView tx_fileName = (TextView)v.findViewById(R.id.txt_fileName);
	                    TextView tx_size = (TextView)v.findViewById(R.id.txt_filePath);
	                    ImageView iv = (ImageView) v.findViewById(R.id.img_fileIcon);
	                    iv.setImageDrawable(res.getDrawable(R.drawable.ic_text));
	                    
	                    CheckBox chkSelect = (CheckBox) v.findViewById(R.id.chkSelectFile);
	                    chkSelect.setChecked(false);

	                	tx_fileName.setText(ffile.getName());
	                	
	                	int temp=Integer.parseInt(ffile.getSize());
	                	if(temp<1024)
	                	{
	                		tx_size.setText(ffile.getSize()+" Byte");   
	                	}
	                	else
	                	{
	                		temp=temp/1024;
	                		tx_size.setText(String.valueOf(temp)+" KB"); 
	                	}
	                	
	
	                }
	                return v;
	            }
			};
			countItemChecked();
	        listview.setAdapter(arrayAdapter);
			super.onPostExecute(result);
		}
	}
	public String getSetting(String key) {
        ShareRef = getSharedPreferences(STRING_NAME_USERSETTING, Context.MODE_WORLD_WRITEABLE);
        return ShareRef.getString(key, "");
	} 	
	
    private void countItemChecked() {
        numberOfItemSelected = 0;
        for (int i = 0; i < listFiles.size(); i++) {
            if (listFiles.get(i).getChecked()) {
                numberOfItemSelected++;
            }
        }
    }
	
    public void convert(ArrayList<FileObject> list){
    	for(int i = 0;i<list.size(); i++){
    		listFiles.add(new myFile(list.get(i).getFileName(),list.get(i).getPathFile(),String.valueOf(list.get(i).getFileSize()), res.getDrawable(R.drawable.ic_text)));
    	}
    }
    
	private void getAllFile(String path){
		try{
			//lay duong dan cua folder chua file restore
			File f= new File(path);
			File[] files= f.listFiles();
			for(int i=0; i<files.length;i++){
				File file = files[i];
				listFiles.add(new myFile(file.getName(),file.getPath(), String.valueOf(file.length()), res.getDrawable(R.drawable.ic_file_selector)));
			}
		}
		catch(Exception e){			
			e.printStackTrace();
		}
	}

	//bat su kien click vao item tren listview
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
//		showToast("item click thu: " +arg2);
//		showToast("duong dan download: " +flist.get(arg2).getPathFile());
		
	}
	
	public void CheckButtonOnClick(View v){
		CheckBox chk = (CheckBox) v;
		int pos = listview.getPositionForView(v);
		myFile file = arrayAdapter.getItem(pos);
		file.setChecked(chk.isChecked());
		numberOfItemSelected += chk.isChecked() ? 1 : -1;
	}

	
	
	public boolean onCreateOptionsMenu(Menu menu) 
	{
	    	// TODO Auto-generated method stub	    	
		new MenuInflater(getApplicationContext()).inflate(R.menu.restore_option_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	public boolean onOptionsItemSelected(MenuItem item) 
	{
	    	// TODO Auto-generated method stub
	    switch(item.getItemId()){
	    case R.id.menu_restore_File:
	    	
	    	if(listFiles.isEmpty()){
	    		showToast("Danh sách trống!");
	    	} else if(numberOfItemSelected <= 0 ){
	    		showToast("Vui lòng chọn danh bạ cần phục hồi!!");
	    	}else if (numberOfItemSelected > 1 )
	    	{
	    		showAlertDialog("Thông báo !", "Bạn chỉ phục hồi một tập tin ", new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
	    	}
	    	else
	    	{
	    		//bắt đầu phục hồi file
	    		showConfirmDialog("Thông báo ", "Bạn có muốn phục hồi danh bạ này ", new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						new AsyncTask<Void, Void, Void>()
						{
							@Override
							protected void onPreExecute() {
								// TODO Auto-generated method stub
								super.onPreExecute();
								loadingContactDialog.show();
							}
							@Override
							protected Void doInBackground(Void... params) {
								// TODO Auto-generated method stub
								String urldownload = "http://"+getSetting("address")+"/ServerWeb/USERS/"+username+"/";
								for(int i=0;i<listFiles.size(); i++){
									myFile mfile = listFiles.get(i);
									FileObject ofile = flist.get(i);
									if(mfile.getChecked()){
										try {
											
											urldownload = urldownload + ofile.getFileName();
//											restoreFromServer(ofile.getPathFile(), ofile.getFileName(), path);
											restoreFromServer(urldownload, ofile.getFileName(), path);
											WebService.writeUserLog(ofile.getFileID(), 2, "phuc hoi tap tin danh ba da sao luu len may chu");
											System.out.println("duong dan tai tap tin(urldownload): "+ urldownload);
											// xử ly giải mã tập tin
											Log.d("path",path);
											aes = new AESControl(username);
											//gỡ đuôi .aes
											String pathTemp=path+"/"+ofile.getFileName();
											Log.d("pathtemp",pathTemp);										
											String output = pathTemp+".dec";
											Log.d("out",output);		
											aes.DecFile(pathTemp, output);
											//xu ly import danh bạ
											//xóa file tam 
											File temp1= new File(pathTemp);
											temp1.delete();
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								}
								return null;
							}
							@Override
							protected void onPostExecute(Void result) {
								// TODO Auto-generated method stub
								loadingContactDialog.dismiss();
								for(int j = 0 ;j <listFiles.size(); j++){
									listFiles.get(j).setChecked(false);					
								}
								numberOfItemSelected = 0;
								arrayAdapter.notifyDataSetChanged();
								super.onPostExecute(result);
								new AlertDialog.Builder(ContactRestoreServerActivity.this).setMessage("Phục hồi Thành Công ")
								.setIcon(R.drawable.ic_info_select).setTitle("Thông Báo").setPositiveButton("Đồng Ý", new OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
										//duyet mang và set check lai false
									
										dialog.dismiss();
									}
								}).show();
							
							}
						}.execute();
					}
				});
	    		
	    	}
	    	return true;
	    case R.id.menu_restore_Delete:
	    	if(listFiles.isEmpty()){
	    		showToast("Danh sách trống!");
	    	} else if(numberOfItemSelected <= 0 ){
	    		showToast("Vui lòng chọn danh bạ cần xóa!");
	    	}else if (numberOfItemSelected > 0 ){
				showConfirmDialog("Xác Nhận Xóa", "Bạn có chắc chắn muốn xóa?", new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						new AsyncTask<Void, Void, Void>()
						{
							@Override
							protected void onPreExecute() {
								// TODO Auto-generated method stub
								loadingContactDialog.show();
								loadingContactDialog.setMessage("Đang xóa tập tin");
								super.onPreExecute();
							}
							@Override
							protected Void doInBackground(Void... params) {
								// TODO Auto-generated method stub
								for(int i=0;i<listFiles.size(); i++){
									myFile mfile = listFiles.get(i);
									FileObject ofile = flist.get(i);
									if(mfile.getChecked()){
										try {
											String msg = WebService.deleteFileById(ofile.getFileID(), "xoa tap tin danh ba da sao luu tren may chu");
											if(msg.equals("1")){
												listFiles.remove(mfile);
												flist.remove(ofile);
												i--;
												numberOfItemSelected --;
											}
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								}
								return null;
							}
							@Override
							protected void onPostExecute(Void result) {
								// TODO Auto-generated method stub
								super.onPostExecute(result);
								loadingContactDialog.dismiss();
								new AlertDialog.Builder(ContactRestoreServerActivity.this).setMessage("Xóa Thành Công ")
								.setIcon(R.drawable.ic_info_select).setTitle("Thông Báo !").setPositiveButton("Đồng Ý", new OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
										//duyet mang và set check lai false
										arrayAdapter.notifyDataSetChanged();
										dialog.cancel();
									}
								}).show();
							}
						}.execute();
						
						
					//	showToast("đã xóa tập tin");
					}
				});
	    	}
	    	return true;
	    case R.id.menu_restore_Logout:	
	    	logOut();
            Intent intent = new Intent(ContactRestoreServerActivity.this, LoginActivity.class);
            startActivity(intent);
            this.finish();
	    	return true;	    	
	    }
	    return false;
	}
	
	private static void restoreFromServer(String url, String fileName, String path){
		try{
			int lenght = 0;				
			File file = new File(path,fileName);	
			FileOutputStream fos = new FileOutputStream(file);
			System.out.println("url download file: "+url);
			System.out.println("path save file : "+path);
			
			//doi tuong urlconnection
	        URL u = new URL(url);
	        URLConnection urlconn = u.openConnection();
	        HttpURLConnection httpconn = (HttpURLConnection) urlconn;
	        httpconn.setRequestMethod("GET");
	        httpconn.setDoOutput(true);
	        httpconn.connect();
	        //lay ve doi tuong va dat trong inputStream
	        InputStream in = httpconn.getInputStream();
			lenght=httpconn.getContentLength();
								
			byte[] buffer = new byte[1024];
	        int len1 = 0;
	        long total = 0;

	        while ((len1 = in.read(buffer)) > 0) {
	            total += len1; 
	            fos.write(buffer, 0, len1);
	        }
	        fos.close();	        			
	        System.out.println("length file: "+file.length());
		}catch (Exception e) {
			// TODO: handle exception
			Log.e("KQ1", e.toString());
		}
	}

}
